const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
const url = "";
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 验证是否为手机
function isMobile(str) {
  var reg = /^1[0-9]{10}$/
  return reg.test(str);
}
// 去除前后空格
function trim(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}
// 格式化时间戳
function timeToDate(timestamp, format = null) {
  if (timestamp != "" && timestamp != null) {
    let date = new Date(timestamp * 1000);
    var o = {
      "M+": date.getMonth() + 1,
      "d+": date.getDate(),
      "h+": date.getHours(),
      "m+": date.getMinutes(),
      "s+": date.getSeconds(),
      "q+": Math.floor((date.getMonth() + 3) / 3),
      "S": date.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      }
    }
    return format;
  } else {
    return "";
  }

}
function dateFormat(date, format) {
  var o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S": date.getMilliseconds()
  }

  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }

  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
}
// 格式化时间戳
function dateFormat2(date) {
  var curYear = dateFormat(new Date(), "yyyy");
  var timeYear = curYear;
  var timeformat = "MM-dd";
  if (!Number.isInteger(date)) {
    timeYear = dateFormat((new Date(date.replace(/-/g, "/"))), "yyyy")
    if (timeYear != curYear) {
      timeformat = "yyyy-MM-dd";
    }
    return dateFormat((new Date(date.replace(/-/g, "/"))), timeformat);
  } else {
    timeYear = timeToDate(date, "yyyy")
    if (timeYear != curYear) {
      timeformat = "yyyy-MM-dd";
    }
    return timeToDate(date, timeformat);
  }

  return timeToDate(date, timeformat);

}


// 日期格式化
function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 显示自定义警告
function showSelfModal(self, msg, t = 2000) {
  self.setData({
    showSelfModal: true,
    errorMsg: msg
  });
  var expressTime = setTimeout(function () {
    clearTimeout(expressTime);
    self.setData({
      showSelfModal: false
    });
  }, t);
}
// 显示自定义通知
function showSelfNotice(self, msg, t = 2000) {
  self.setData({
    showSelfNotice: true,
    noticeMsg: msg
  });
  var expressTime = setTimeout(function () {
    clearTimeout(expressTime);
    self.setData({
      showSelfNotice: false
    });
  }, t);
}
// 显示自定义通知
function showAlert(self) {
  self.setData({
    showAlert: true
  });
}

function showModalSys(msg,callback){
  wx.showModal({
    title: '提示',
    content: msg,
    success (res) {
      if (res.confirm) {
        callback(res);
      } else if (res.cancel) {
          wx.hideToast();
      }
    }
  })
}
function showTip(self, msg, success, t = 2000) {
  self.setData({
    showTip: true,
    showTipSuccess: success,
    showTipMsg: msg
  });
  var expressTime = setTimeout(function () {
    clearTimeout(expressTime);
    self.setData({
      showTip: false
    });
  }, t);
}

function selfLoading() {
  let available = wx.canIUse('showLoading');
  if (available) {
    wx.showLoading({
      title: '加载中',
    })
  } else {
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration: 10000
    })
  }
}

function selfHideLoading() {
  let available = wx.canIUse('showLoading');
  if (available) {
    wx.hideLoading();

  } else {
    wx.hideToast();
  }
}

function curTime() {
  return parseInt(Date.parse(new Date()) / 1000);
}

function getAddTime(add_day){
  var dateTime=new Date();
  dateTime=dateTime.setDate(dateTime.getDate()+add_day);
  dateTime=timeToDate(dateTime/1000,"M月dd日")
  return dateTime;
}

function arrayToJson(o) {
  var r = [];
  if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
  if (typeof o == "object") {
    if (!o.sort) {
      for (var i in o)
        r.push(i + ":" + arrayToJson(o[i]));
      if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
        r.push("toString:" + o.toString.toString());
      }
      r = "{" + r.join() + "}";
    } else {
      for (var i = 0; i < o.length; i++) {
        r.push(arrayToJson(o[i]));
      }
      r = "[" + r.join() + "]";
    }
    return r;
  }
  return o.toString();
}


module.exports = {
  dateFormat: dateFormat,
  isMobile: isMobile,
  trim: trim,
  showSelfModal: showSelfModal,
  showSelfNotice: showSelfNotice,
  selfLoading: selfLoading,
  selfHideLoading: selfHideLoading,
  timeToDate: timeToDate,
  showAlert: showAlert,
  showTip: showTip,
  formatNumber: formatNumber,
  curTime: curTime,
  dateFormat2: dateFormat2,
  formatTime: formatTime,
  parseTime: parseTime,
  showModalSys:showModalSys,
  getAddTime:getAddTime
}
